﻿using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace DNFImagePacks2Manager.Helpers
{
    // 版本工具
    public class VersionHelper
    {

        private static readonly Version version = new("2.5.3");
        private static readonly string UpdateUrl = "http://www.tripleying.com/dnf/ipm/get-update-latest";

        public static string GetVersionString() { return version.ToString(); }

        public static async Task UpdateCheck(Page page, bool onlyNewest)
        {
            try
            {
                HttpClient HttpClient = new();
                string jsonString = await HttpClient.GetStringAsync(UpdateUrl).ConfigureAwait(false);
                UpdateResponse? response = JsonConvert.DeserializeObject<UpdateResponse>(jsonString);
                if (response == null || response.Code != 200 || response.Data == null)
                {
                    ShowStatusMessage(page, onlyNewest, false, "访问更新检查服务器失败");
                    return;
                }

                if (!Version.TryParse(response.Data.VersionString, out Version? remoteVersion))
                {
                    ShowStatusMessage(page, onlyNewest, false, "版本号解析失败");
                    return;
                }

                if(remoteVersion.CompareTo(version) > 0)
                {
                    page.DispatcherQueue?.TryEnqueue(() =>
                    { 
                        string info = response.Data.UpdateInfo;
                        var infoList = info.Split(["<br>"], StringSplitOptions.RemoveEmptyEntries);
                        var listView = new ListView
                        {
                            ItemsSource = infoList,

                            Margin = new Thickness(0, 12, 0, 0),
                            BorderThickness = new Thickness(0),
                            Background = null
                        };
                        DialogHelper.ShowNormalDialog(
                            page,
                            $"检查到新版本: v{response.Data.VersionString} - {response.Data.UpdateDate.Split(" ")[0]}" ,
                            listView);
                    });
                }
                else
                {
                    ShowStatusMessage(page, onlyNewest, true, "已经是最新版本");
                }
            }
            catch (Exception ex)
            {
                string errorMessage = ex switch
                {
                    HttpRequestException => "网络请求失败",
                    JsonException => "版本数据解析失败",
                    _ => "检查更新失败"
                };
                ShowStatusMessage(page, onlyNewest, false, $"{errorMessage}: {ex.Message}");
            }
        }

        private static void ShowStatusMessage(Page page, bool onlyNewest, bool isSuccess, string message)
        {
            if (onlyNewest)
            {
                return;
            }

            page.DispatcherQueue?.TryEnqueue(() =>
            {
                if (isSuccess)
                {
                    DialogHelper.ShowSuccessMessage(page, message);
                }
                else
                {
                    DialogHelper.ShowErrorMessage(page, message);
                }
            });
        }
    }

    public class UpdateResponse
    {
        [JsonProperty("code")]
        public int Code { get; set; }

        [JsonProperty("msg")]
        public string Message { get; set; } = string.Empty;

        [JsonProperty("data")]
        public UpdateData? Data { get; set; }
    }

    public class UpdateData
    {
        [JsonProperty("updateDate")]
        public string UpdateDate { get; set; } = string.Empty;

        [JsonProperty("version")]
        public string VersionString { get; set; } = string.Empty;

        [JsonProperty("updateInfo")]
        public string UpdateInfo { get; set; } = string.Empty;
    }
}
